﻿using MyMVC.mapper;
using MyMVC.util;
using System.Reflection;
using System.Web;
using MyUtils;
using System.Text;

namespace MyMVC.handler
{
    public class JsonHandler : BaseHandler
    {
        public JsonHandler(HttpContext context, MethodInfo method, ActionSupport baseType)
        {
            this.method = method;
            this.baseType = baseType;
        }

        public override void process(HttpContext context)
        {
            JSON json = (JSON)method.Invoke(baseType, null);
            context.Response.ContentType = "application/json;charset=utf-8";
            string str = JSONHelper.serialize(json.getData());
            if (WebContextUtils.isGZip(context.Request))
            {
                byte[] rawData = Encoding.UTF8.GetBytes(str);
                if (rawData.Length > 256)
                {
                    context.Response.AddHeader("Content-Encoding", "gzip");
                    context.Response.BinaryWrite(GZipUtils.Compress(rawData));
                    context.Response.End();
                }
            }
            context.Response.Write(str);
            context.Response.End();
        }
    }
}
